<!--生产报工-->
<template>
  <div class="production-reporting-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>报工单号</label>
        <input v-model="query.reportNo" type="text" placeholder="请输入报工单号">
      </div>
      <div class="filter-item">
        <label>工序名称</label>
        <input v-model="query.processName" type="text" placeholder="请输入工序名称">
      </div>
      <div class="filter-item">
        <label>工序编码</label>
        <input v-model="query.processCode" type="text" placeholder="请输入工序编码">
      </div>
      <div class="filter-item">
        <label>关联工单</label>
        <input v-model="query.relatedWorkOrder" type="text" placeholder="请输入关联工单">
      </div>
      <div class="filter-item">
        <label>执行人</label>
        <input v-model="query.username" type="text" placeholder="请输入执行人">
      </div>
      <div class="filter-item">
        <label>班组</label>
        <input v-model="query.workGroup" type="text" placeholder="请输入班组">
      </div>
      <div class="filter-item">
        <label>质检状态</label>
        <select v-model="query.qcStatus">
          <option :value="''">全部</option>
          <option :value="0">未质检</option>
          <option :value="1">合格</option>
          <option :value="2">返工</option>
          <option :value="3">报废</option>
        </select>
      </div>
      <div class="filter-item">
        <label>开始日期</label>
        <input v-model="query.startDate" type="date">
      </div>
      <div class="filter-item">
        <label>结束日期</label>
        <input v-model="query.endDate" type="date">
      </div>
      <div class="filter-buttons">
        <button class="btn-primary" @click="handleSearch">搜索</button>
        <button class="btn-secondary" @click="handleReset">重置</button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="btn-primary" @click="openCreate">新建</button>
      <button class="btn-secondary" @click="exportSelected">导出</button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>报工单号</th>
            <th>工序</th>
            <th>关联工单</th>
            <th>数量</th>
            <th>执行人</th>
            <th>班组</th>
            <th>报工日期</th>
            <th>质检状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="item.id || index">
            <td><input type="checkbox" v-model="item._selected"></td>
            <td>{{ item.reportNo || '-' }}</td>
            <td>{{ item.processName || '-' }} <span class="process-code">{{ item.processCode }}</span></td>
            <td>{{ item.relatedWorkOrder || '-' }}</td>
            <td>{{ item.quantity || 0 }}</td>
            <td>{{ item.username || '-' }}</td>
            <td>{{ item.workGroup || '-' }}</td>
            <td>{{ formatDate(item.reportDate) }}</td>
            <td>{{ formatQcStatus(item.qcStatus) }}</td>
            <td>
              <button class="btn-secondary" @click="viewDetail(item)">详情</button>
              <button class="btn-secondary" @click="openEdit(item)">编辑</button>
              <button class="btn-secondary" @click="handleDelete(item.id)">删除</button>
            </td>
          </tr>
          <tr v-if="tableData.length === 0">
            <td colspan="10" style="text-align:center;color:#909399;">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary" @click="exportSelected">导出</button>
      </div>
      <div class="pagination">
        <button :disabled="page.current === 1" @click="changePage(page.current - 1)">&lt;</button>
        <span style="padding:0 8px;">第 {{ page.current }} / {{ totalPages }} 页</span>
        <button :disabled="page.current === totalPages || total === 0" @click="changePage(page.current + 1)">&gt;</button>
        <select v-model.number="page.size" @change="changeSize">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
        <span style="padding-left:8px;">共 {{ total }} 条</span>
      </div>
    </div>

    <!-- 简单新增/编辑弹窗 -->
    <div v-if="dialog.visible" class="dialog-mask">
      <div class="dialog-panel">
        <div class="dialog-header">{{ dialog.mode === 'create' ? '新建报工' : '编辑报工' }}</div>
        <div class="dialog-body">
          <div class="form-row">
            <label>报工单号</label>
            <input v-model="dialog.form.reportNo" placeholder="自动或手填">
          </div>
          <div class="form-row">
            <label>工序名称</label>
            <input v-model="dialog.form.processName">
          </div>
          <div class="form-row">
            <label>工序编码</label>
            <input v-model="dialog.form.processCode">
          </div>
          <div class="form-row">
            <label>关联工单</label>
            <input v-model="dialog.form.relatedWorkOrder">
          </div>
          <div class="form-row">
            <label>数量</label>
            <input v-model.number="dialog.form.quantity" type="number" min="0">
          </div>
          <div class="form-row">
            <label>执行人</label>
            <input v-model="dialog.form.username">
          </div>
          <div class="form-row">
            <label>班组</label>
            <input v-model="dialog.form.workGroup">
          </div>
          <div class="form-row">
            <label>报工日期</label>
            <input v-model="dialog.form.reportDate" type="date">
          </div>
          <div class="form-row">
            <label>质检状态</label>
            <select v-model.number="dialog.form.qcStatus">
              <option :value="0">未质检</option>
              <option :value="1">合格</option>
              <option :value="2">返工</option>
              <option :value="3">报废</option>
            </select>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeDialog">取消</button>
          <button class="btn-primary" @click="submitDialog">确定</button>
        </div>
      </div>
    </div>

    <!-- 详情弹窗（网格布局展示） -->
    <div v-if="detailDialog.visible" class="dialog-mask">
      <div class="dialog-panel" style="width: 720px;">
        <div class="dialog-header">报工详情</div>
        <div class="dialog-body">
          <div class="detail-grid">
            <div class="detail-item"><span class="label">报工单号</span><span class="value">{{ detailDialog.data.reportNo || '-' }}</span></div>
            <div class="detail-item"><span class="label">工序名称</span><span class="value">{{ detailDialog.data.processName || '-' }}</span></div>
            <div class="detail-item"><span class="label">工序编码</span><span class="value">{{ detailDialog.data.processCode || '-' }}</span></div>
            <div class="detail-item"><span class="label">关联工单</span><span class="value">{{ detailDialog.data.relatedWorkOrder || '-' }}</span></div>
            <div class="detail-item"><span class="label">报工数量</span><span class="value">{{ detailDialog.data.quantity ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">良品数</span><span class="value">{{ detailDialog.data.goodProductNumber ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">不良数量</span><span class="value">{{ detailDialog.data.scrappedQuantity ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">返工数量</span><span class="value">{{ detailDialog.data.numberRework ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">返工率</span><span class="value">{{ detailDialog.data.reworkRate ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">报废率</span><span class="value">{{ detailDialog.data.scrapRate ?? '-' }}</span></div>
            <div class="detail-item"><span class="label">质检状态</span><span class="value">{{ formatQcStatus(detailDialog.data.qcStatus) }}</span></div>
            <div class="detail-item"><span class="label">报工日期</span><span class="value">{{ formatDate(detailDialog.data.reportDate) }}</span></div>
            <div class="detail-item"><span class="label">班组</span><span class="value">{{ detailDialog.data.workGroup || '-' }}</span></div>
            <div class="detail-item"><span class="label">执行人</span><span class="value">{{ detailDialog.data.username || '-' }}</span></div>
            <div class="detail-item detail-span-2"><span class="label">问题描述</span><span class="value">{{ detailDialog.data.problemDescription || '-' }}</span></div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-primary" @click="detailDialog.visible = false">我知道了</button>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { productionReportingApi } from '../../api/productionReporting'

export default {
  name: 'ProductionReporting',
  data() {
    return {
      query: {
        reportNo: '',
        processName: '',
        processCode: '',
        relatedWorkOrder: '',
        username: '',
        workGroup: '',
        qcStatus: '',
        startDate: '',
        endDate: '',
      },
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      tableData: [],
      loading: false,
      dialog: {
        visible: false,
        mode: 'create', // create | edit
        form: {
          id: undefined,
          reportNo: '',
          processName: '',
          processCode: '',
          relatedWorkOrder: '',
          quantity: 0,
          username: '',
          workGroup: '',
          reportDate: '',
          qcStatus: 0,
        },
      },
      detailDialog: {
        visible: false,
        data: {},
      },
    }
  },
  computed: {
    allSelected: {
      get() {
        return this.tableData.length > 0 && this.tableData.every((item) => item._selected)
      },
      set(value) {
        this.tableData.forEach((item) => {
          item._selected = value
        })
      },
    },
    totalPages() {
      if (this.page.size <= 0) return 1
      return Math.max(1, Math.ceil(this.total / this.page.size))
    },
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.page.current,
          pageSize: this.page.size,
          ...this.query,
        }
        const res = await productionReportingApi.getPage(params)
        const payload = res?.data
        // 兼容两种返回结构：{records,total,current,size} 或 {data:{records,total,...}}
        const pageData = payload?.data && payload.data.records ? payload.data : payload
        const rawRecords = pageData?.records || []
        this.total = Number(pageData?.total || 0)
        this.page.current = Number(pageData?.current || params.pageNum)
        this.page.size = Number(pageData?.size || params.pageSize)
        // 将后端 snake_case 字段映射为前端使用的 camelCase 字段
        this.tableData = rawRecords.map((it) => {
          const mapped = {
            // 关键主键
            id: it.id ?? it.report_id ?? it.primary_id,
            // 基础展示字段
            reportNo: it.reportNo ?? it.report_no,
            processName: it.processName ?? it.process_name,
            processCode: it.processCode ?? it.process_code,
            relatedWorkOrder: it.relatedWorkOrder ?? it.related_work_order,
            // 数量优先使用报工数量，其次良品数
            quantity: it.quantity ?? it.report_quantity ?? it.good_product_number ?? 0,
            username: it.username ?? it.executor ?? it.report_user ?? it.user_name,
            workGroup: it.workGroup ?? it.work_group ?? it.team,
            reportDate: it.reportDate ?? it.date_report ?? it.report_date,
            qcStatus: typeof it.qcStatus === 'number' ? it.qcStatus : (typeof it.qc_status === 'number' ? it.qc_status : undefined),
          }
          return { ...it, ...mapped, _selected: false }
        })
      } catch (e) {
        // 已有全局错误提示
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.page.current = 1
      this.loadData()
    },
    handleReset() {
      this.query = {
        reportNo: '',
        processName: '',
        processCode: '',
        relatedWorkOrder: '',
        username: '',
        workGroup: '',
        qcStatus: '',
        startDate: '',
        endDate: '',
      }
      this.page.current = 1
      this.loadData()
    },
    changePage(p) {
      if (p < 1 || p > this.totalPages) return
      this.page.current = p
      this.loadData()
    },
    changeSize() {
      this.page.current = 1
      this.loadData()
    },
    formatDate(v) {
      if (!v) return '-'
      try {
        const d = new Date(v)
        if (Number.isNaN(d.getTime())) return v
        const mm = String(d.getMonth() + 1).padStart(2, '0')
        const dd = String(d.getDate()).padStart(2, '0')
        return `${d.getFullYear()}-${mm}-${dd}`
      } catch (_) {
        return v
      }
    },
    formatQcStatus(s) {
      const map = { 0: '未质检', 1: '合格', 2: '返工', 3: '报废' }
      return map[s] ?? '-'
    },
    exportSelected() {
      const selected = this.tableData.filter((x) => x._selected)
      if (selected.length === 0) {
        ElMessage.info('请先选择要导出的数据')
        return
      }
      // 简单导出为 JSON 文件
      const blob = new Blob([JSON.stringify(selected, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `生产报工_${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
    },
    async viewDetail(row) {
      const id = row?.id ?? row?.report_id ?? row?.primary_id
      let detail = null
      if (id) {
        try {
          const res = await productionReportingApi.getById(id)
          detail = res?.data?.data || res?.data || row
        } catch (e) {
          detail = row
        }
      } else {
        detail = row
      }
      // 统一映射字段，便于展示
      const m = detail || {}
      this.detailDialog.data = {
        reportNo: m.reportNo ?? m.report_no,
        processName: m.processName ?? m.process_name,
        processCode: m.processCode ?? m.process_code,
        relatedWorkOrder: m.relatedWorkOrder ?? m.related_work_order,
        quantity: m.quantity ?? m.report_quantity ?? m.good_product_number,
        goodProductNumber: m.good_product_number ?? m.goodProductNumber,
        numberRework: m.number_rework ?? m.numberRework,
        scrappedQuantity: m.scrapped_quantity ?? m.scrappedQuantity,
        reworkRate: m.rework_rate ?? m.reworkRate,
        scrapRate: m.scrap_rate ?? m.scrapRate,
        problemDescription: m.problem_description ?? m.problemDescription,
        qcStatus: typeof m.qcStatus === 'number' ? m.qcStatus : m.qc_status,
        reportDate: m.reportDate ?? m.date_report ?? m.report_date,
        workGroup: m.workGroup ?? m.work_group,
        username: m.username ?? m.executor ?? m.report_user ?? m.user_name,
      }
      this.detailDialog.visible = true
    },
    openCreate() {
      this.dialog.mode = 'create'
      this.dialog.form = {
        id: undefined,
        reportNo: '',
        processName: '',
        processCode: '',
        relatedWorkOrder: '',
        quantity: 0,
        username: '',
        workGroup: '',
        reportDate: '',
        qcStatus: 0,
      }
      this.dialog.visible = true
    },
    openEdit(row) {
      this.dialog.mode = 'edit'
      this.dialog.form = {
        id: row.id,
        reportNo: row.reportNo || '',
        processName: row.processName || '',
        processCode: row.processCode || '',
        relatedWorkOrder: row.relatedWorkOrder || '',
        quantity: row.quantity || 0,
        username: row.username || '',
        workGroup: row.workGroup || '',
        reportDate: row.reportDate ? this.formatDate(row.reportDate) : '',
        qcStatus: typeof row.qcStatus === 'number' ? row.qcStatus : 0,
      }
      this.dialog.visible = true
    },
    closeDialog() {
      this.dialog.visible = false
    },
    async submitDialog() {
      const payload = { ...this.dialog.form }
      try {
        if (this.dialog.mode === 'create') {
          await productionReportingApi.add(payload)
          ElMessage.success('新增成功')
        } else {
          await productionReportingApi.update(payload)
          ElMessage.success('更新成功')
        }
        this.dialog.visible = false
        this.loadData()
      } catch (e) {}
    },
    async handleDelete(id) {
      try {
        await ElMessageBox.confirm('确定删除该记录吗？', '提示', { type: 'warning' })
      } catch (_) {
        return
      }
      try {
        await productionReportingApi.remove(id)
        ElMessage.success('删除成功')
        this.loadData()
      } catch (e) {}
    },
  },
}
</script>

<style scoped>
.production-reporting-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-section {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: flex-start;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 320px;
  margin-bottom: 12px;
}

.filter-item label {
  font-size: 14px;
  width: 72px;
  text-align: right;
  white-space: nowrap;
}

.filter-item input,
.filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 220px;
  box-sizing: border-box;
}

.filter-buttons {
  margin-left: auto;
  align-self: center;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

tbody tr:hover {
  background: #fafcff;
}
tbody tr:nth-child(odd) {
  background: #fcfcfd;
}

.process-code, .work-order-code {
  color: #909399;
  font-size: 12px;
  display: block;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 简易弹窗样式 */
.dialog-mask {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.dialog-panel {
  width: 520px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.dialog-header {
  padding: 12px 16px;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}
.dialog-body {
  padding: 16px;
}
.dialog-footer {
  padding: 12px 16px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}
.form-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}
.form-row label {
  width: 88px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}
.form-row input,
.form-row select {
  flex: 1;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 详情网格样式 */
.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  column-gap: 16px;
  row-gap: 12px;
}
.detail-item {
  display: flex;
  align-items: center;
}
.detail-item .label {
  width: 96px;
  flex: 0 0 96px;
  color: #606266;
  text-align: right;
  margin-right: 8px;
}
.detail-item .value {
  color: #303133;
}
.detail-span-2 {
  grid-column: span 2;
}
</style>
